/**
 * @Description:
 * @Author: FangYaoTang
 * @Date: 2023-08-16 09:14:09
 * @LastEditor: FangYaoTang
 * @LastEditTime: 2023-09-12 10:43:42
 * @Copyright: by 南京桓羽信息科技有限公司 禁止任何形式（包含二次开发）转售系统源码，违者必究。
 */

import apiList from './api.js'
import { BASE_URL, SIGN } from '@/env.js'
import store from '@/common/store/index.js'

// 组装接口路径
const getApiPath = (path) => {
  let apiArray = path.split('.'),
    api = apiList
  apiArray.forEach((v) => {
    api = api[v]
  })
  return api
}

const tabbar = [
  'pages/home/index',
  'pages/home/watch',
  'pages/videoWebView/recommend',
  'pages/home/user'
]

// 发起请求的函数
const request = (path, data, error = true) => {
  if (!BASE_URL) {
    uni.showModal({ title: '未检测到域名地址，请联系管理员' })
    throw '未检测到域名, 已阻止此次API请求'
  }
  const api = path.indexOf('http') == -1 ? getApiPath(path) : { url: path, method: 'GET' }
  
  if (!api) throw '接口未定义, 已阻止此次API请求'
  let url = BASE_URL + api.url,
    method = api.method || 'POST'
  // uni.showToast({title: url.indexOf('logoff') != -1 ? url + data : '', icon: 'none'})
  if (url.indexOf('logoff') != -1) {
    url = url + data
  }
  // 通过Promise封装请求, 返回异步请求结果
  return new Promise(async (resolve, reject) => {
    uni.request({
      url: path.indexOf('http') == -1 ? url : path,
      data: {
        ...data,
        language: 'en'
      },
      method,
      header: {
        // 'Content-Type': method === 'GET' ? 'application/json' : 'application/x-www-form-urlencoded',
        Token: store.state.user.token || ''
        // 'Sign': SIGN || ''
      },

      success: (res) => {
        const page = getCurrentPages()
        console.log(res, page, 'request success 2222')
        if (res.statusCode === 200) {
          if (res.data && res.data.code == 401) {
            store.dispatch('user/logout')
            uni.redirectTo({ url: '/pages/login/login' })
            reject()
            // error &&
            //   uni.showModal({
            //     title: 'Login prompt',
            //     content: 'You have not logged in yet, please log in first',
            //     cancelText: 'Cancel',
            //     confirmText: 'Confirm',
            //     success: (res) => {
            //       if (res.confirm) {
            //         uni.redirectTo({ url: '/pages/login/login' })
            //       } else {
            //         if (!tabbar.includes(page[page.length - 1].route)) {
            //           wx.navigateBack()
            //         }
            //       }
            //       reject()
            //     }
            //   })
          } else if (res.data.code && res.data.code != '0000') {
            uni.showToast({
              title: res.data.msg,
              icon: 'none'
            })
            reject(res.data)
            return
          }
        } else if (res.statusCode === 401) {
          // if(res.data.code == 401) {
          store.dispatch('user/logout')
          uni.redirectTo({ url: '/pages/login/login' })
          reject()
          // error &&
          //   uni.showModal({
          //     title: 'Login prompt',
          //     content: 'You have not logged in yet, please log in first',
          //     cancelText: 'Cancel',
          //     confirmText: 'Confirm',
          //     success: (res) => {
          //       if (res.confirm) {
          //         uni.redirectTo({ url: '/pages/login/login' })
          //       } else {
          //         if (!tabbar.includes(page[page.length - 1].route)) {
          //           wx.navigateBack()
          //         }
          //       }
          //       reject()
          //     }
          //   })
          // }
        } else {
          uni.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
        resolve(res.data || res)
      },
      fail: (err) => {
        console.log(err, '111111111111')
        uni.showToast({
          title: err.errMsg,
          icon: 'none',
          duration: 3000
        })
        // uni.showToast({
        // 	title: `服务器开小差 => ${BASE_URL || 'NULL'} => ${SIGN || 'NULL'}`,
        // 	icon: 'none'
        // })
        reject(err)
      }
    })
  })
}

export default request
